package com.zyx.netty.codec;

import com.zyx.constants.Constants;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 根据请求报文和响应报文，动态设置http的编码器和解码器
 *
 * @author DQing
 * @version 1.0
 * @className DynamicHttpCodec
 * @date 2020/3/31 14:28
 */
@Slf4j
public class DynamicHttpCodec {

    /**
     * 根据请求报文，添加对应的http解码器
     * @param pipeline
     * @param isRequested
     */
    public static void requestHandler(ChannelPipeline pipeline, boolean isRequested){
        log.info("当前请求的handler:{}",pipeline.toMap().toString());
        if(isRequested){
            if(pipeline.get(Constants.RESPONSE_HANDLER_DECODER)!=null){
                pipeline.remove(Constants.RESPONSE_HANDLER_DECODER);
            }
            if(pipeline.get(Constants.REQUEST_HANDLER_DECODER)==null){
                pipeline.addAfter(Constants.DECODER_HANDLER,
                        Constants.REQUEST_HANDLER_DECODER,
                        new HttpRequestDecoder());
            }
        }else {
            if(pipeline.get(Constants.REQUEST_HANDLER_DECODER)!=null){
                pipeline.remove(Constants.REQUEST_HANDLER_DECODER);
            }
            if(pipeline.get(Constants.RESPONSE_HANDLER_ENCODER)==null){
                pipeline.addAfter(Constants.DECODER_HANDLER,
                        Constants.RESPONSE_HANDLER_DECODER,
                        new HttpResponseDecoder());
            }
        }
    }

    /**
     * 根据响应报文，添加对应的http编码器
     * @param pipeline
     * @param isRequested
     */
    public static void responseHandler(ChannelPipeline pipeline, boolean isRequested){
        log.info("当前请求的handler:{}",pipeline.toMap().toString());
        if(isRequested){
            if(pipeline.get(Constants.RESPONSE_HANDLER_ENCODER)!=null){
                pipeline.remove(Constants.RESPONSE_HANDLER_ENCODER);
            }
            if(pipeline.get(Constants.REQUEST_HANDLER_ENCODER)==null){
                pipeline.addBefore(Constants.REQUEST_HANDLER,
                        Constants.REQUEST_HANDLER_ENCODER,
                        new HttpRequestEncoder());
            }
        }else {
            if(pipeline.get(Constants.REQUEST_HANDLER_ENCODER)!=null){
                pipeline.remove(Constants.REQUEST_HANDLER_ENCODER);
            }
            if(pipeline.get(Constants.RESPONSE_HANDLER_ENCODER)==null){
                pipeline.addBefore(Constants.REQUEST_HANDLER,
                        Constants.RESPONSE_HANDLER_ENCODER,
                        new HttpResponseEncoder());
            }
        }
    }

}
